<template>
  <div class="app-container">
    <!-- 顶部标题和用户信息 -->
    <div class="header">
      <h1>商品进出库历史记录管理系统</h1>
      <el-button type="text" icon="el-icon-user">{{ userInfo.name }}</el-button>
    </div>
    
    <!-- 统计卡片区域 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <stat-card title="总入库数量" :value="statistics.totalIn" unit="件" icon="el-icon-sold-out" color="#67C23A" />
        </el-col>
        <el-col :span="6">
          <stat-card title="总出库数量" :value="statistics.totalOut" unit="件" icon="el-icon-sold-out" color="#E6A23C" />
        </el-col>
        <el-col :span="6">
          <stat-card title="库存余量" :value="statistics.remainTotal" unit="件" icon="el-icon-box" color="#409EFF" />
        </el-col>
        <el-col :span="6">
          <stat-card title="商品种类" :value="statistics.productCount" unit="种" icon="el-icon-s-goods" color="#F56C6C" />
        </el-col>
      </el-row>
    </div>
    
    <!-- 错误信息提示 -->
    <div v-if="errorMessage" class="error-message">
      <el-alert :title="errorMessage" type="error" show-icon :closable="true" @close="errorMessage = ''" />
    </div>
    
    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <div slot="header" class="clearfix">
        <span>筛选条件</span>
      </div>
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="公司名称">
          <el-input
            v-model="searchForm.location"
            placeholder="请输入公司名称"
            prefix-icon="el-icon-office-building"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商品名称"
            prefix-icon="el-icon-s-goods"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operationType" placeholder="全部" clearable>
            <el-option label="入库" value="in" />
            <el-option label="出库" value="out" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh-left" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增记录</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="selectedRecords.length === 0"
        @click="batchDelete"
      >
        批量删除({{ selectedRecords.length }})
      </el-button>
    </div>
    
    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="paginatedData"
        style="width: 100%"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" sortable />
        <el-table-column prop="location" label="公司名称" min-width="150" sortable />
        <el-table-column prop="name" label="商品名称" min-width="120" sortable />
        <el-table-column prop="type" label="商品类型" min-width="120">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作类型" min-width="110" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.in_number > 0 ? 'success' : 'danger'" effect="dark">
              {{ scope.row.in_number > 0 ? '入库' : '出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="数量" min-width="100" align="center">
          <template slot-scope="scope">
            <span :class="scope.row.in_number > 0 ? 'in-number' : 'out-number'">
              {{ scope.row.in_number > 0 ? `+${scope.row.in_number}` : `-${scope.row.out_number}` }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="remain" label="库存余量" min-width="100" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="add_user" label="操作人" min-width="100" />
        <el-table-column prop="add_time" label="操作时间" min-width="150" sortable />
        <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" min-width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        class="pagination-container"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredRecords.length"
      />
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <record-dialog
      :visible="dialogVisible"
      :data="formData"
      :title="dialogTitle"
      @close="dialogVisible = false"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import axios from 'axios';

// 统计卡片组件
const StatCard = {
  props: ['title', 'value', 'unit', 'icon', 'color'],
  render(h) {
    return h('div', { class: 'stat-card' }, [
      h('div', { class: 'stat-content' }, [
        h('div', { class: 'stat-title' }, this.title),
        h('div', { class: 'stat-value' }, [
          h('span', { class: 'value' }, this.value),
          h('span', { class: 'unit' }, this.unit)
        ])
      ]),
      h('div', { class: 'stat-icon', style: { backgroundColor: this.color } }, [
        h('i', { class: this.icon })
      ])
    ]);
  }
};

// 新增/编辑记录对话框组件
const RecordDialog = {
  props: ['visible', 'data', 'title'],
  render(h) {
    return h('el-dialog', {
      props: {
        title: this.title,
        visible: this.visible,
        width: '50%',
        'before-close': this.handleClose,
        'destroy-on-close': true
      },
      on: {
        close: this.close
      }
    }, [
      h('el-form', {
        props: {
          model: this.data,
          labelWidth: '120px',
          rules: this.rules
        },
        ref: 'form'
      }, [
        h('el-form-item', {
          props: {
            label: '公司名称',
            prop: 'location'
          }
        }, [
          h('el-input', {
            props: {
              value: this.data.location,
              placeholder: '输入公司名称'
            },
            on: {
              input: val => { this.data.location = val; }
            }
          })
        ]),
        
        h('el-row', {}, [
          h('el-col', { props: { span: 12 } }, [
            h('el-form-item', {
              props: {
                label: '商品名称',
                prop: 'name'
              }
            }, [
              h('el-input', {
                props: {
                  value: this.data.name,
                  placeholder: '输入商品名称'
                },
                on: {
                  input: val => { this.data.name = val; }
                }
              })
            ])
          ]),
          
          h('el-col', { props: { span: 12 } }, [
            h('el-form-item', {
              props: {
                label: '商品类型',
                prop: 'type'
              }
            }, [
              h('el-select', {
                props: {
                  value: this.data.type,
                  placeholder: '选择商品类型',
                  style: 'width: 100%'
                },
                on: {
                  input: val => { this.data.type = val; }
                }
              }, [
                ...['电子产品', '食品', '服装', '日用品', '办公用品', '建材'].map(item => 
                  h('el-option', { props: { label: item, value: item } })
                )
              ])
            ])
          ])
        ]),
        
        h('el-row', {}, [
          h('el-col', { props: { span: 12 } }, [
            h('el-form-item', {
              props: {
                label: '操作类型',
                prop: 'operation'
              }
            }, [
              h('el-radio-group', {
                props: {
                  value: this.data.operation
                },
                on: {
                  input: val => { 
                    this.data.operation = val;
                    this.data.quantity = 1;
                  }
                }
              }, [
                h('el-radio-button', { props: { label: 'in' } }, '入库'),
                h('el-radio-button', { props: { label: 'out' } }, '出库')
              ])
            ])
          ]),
          
          h('el-col', { props: { span: 12 } }, [
            h('el-form-item', {
              props: {
                label: this.data.operation === 'in' ? '入库数量' : '出库数量',
                prop: 'quantity'
              }
            }, [
              h('el-input-number', {
                props: {
                  value: this.data.quantity,
                  min: 1,
                  precision: 0,
                  controlsPosition: 'right',
                  style: 'width: 200px'
                },
                on: {
                  input: val => { this.data.quantity = val; }
                }
              }),
              h('span', { style: 'margin-left: 10px; color: #888' }, this.data.unit)
            ])
          ])
        ]),
        
        h('el-row', {}, [
          h('el-col', { props: { span: 12 } }, [
            h('el-form-item', {
              props: {
                label: '操作人',
                prop: 'add_user'
              }
            }, [
              h('el-input', {
                props: {
                  value: this.data.add_user,
                  placeholder: '输入操作人姓名'
                },
                on: {
                  input: val => { this.data.add_user = val; }
                }
              })
            ])
          ]),
          
          h('el-col', { props: { span: 12 } }, [
            h('el-form-item', {
              props: {
                label: '操作时间',
                prop: 'add_time'
              }
            }, [
              h('el-date-picker', {
                props: {
                  type: 'datetime',
                  value: this.data.add_time,
                  placeholder: '选择操作时间',
                  valueFormat: 'yyyy-MM-dd HH:mm:ss',
                  style: 'width: 100%'
                },
                on: {
                  input: val => { this.data.add_time = val; }
                }
              })
            ])
          ])
        ]),
        
        h('el-form-item', {
          props: {
            label: '备注',
          }
        }, [
          h('el-input', {
            props: {
              type: 'textarea',
              rows: 3,
              value: this.data.remark,
              placeholder: '输入备注信息'
            },
            on: {
              input: val => { this.data.remark = val; }
            }
          })
        ])
      ]),
      
      h('div', { slot: 'footer', class: 'dialog-footer' }, [
        h('el-button', { on: { click: this.close } }, '取 消'),
        h('el-button', { props: { type: 'primary' }, on: { click: this.submit } }, '确 定')
      ])
    ]);
  },
  data() {
    return {
      rules: {
        location: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择商品类型', trigger: 'change' }
        ],
        operation: [
          { required: true, message: '请选择操作类型', trigger: 'change' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
        ],
        add_user: [
          { required: true, message: '请输入操作人', trigger: 'blur' }
        ],
        add_time: [
          { required: true, message: '请选择操作时间', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    close() {
      this.$emit('close');
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('submit');
          this.close();
        } else {
          return false;
        }
      });
    },
    handleClose(done) {
      this.close();
      done();
    }
  }
};

export default {
  name: 'InventoryHistory',
  components: {
    StatCard,
    RecordDialog
  },
  data() {
    return {
      loading: false,
      userInfo: {
        id: 1,
        name: '管理员',
        role: 'admin'
      },
      statistics: {
        totalIn: 0,
        totalOut: 0,
        remainTotal: 0,
        productCount: 0
      },
      errorMessage: '',
      records: [],          // 从后端获取的所有记录
      filteredRecords: [],  // 筛选后的记录
      selectedRecords: [],  // 当前选中的记录
      searchForm: {
        location: '',
        name: '',
        operationType: '',
        dateRange: []
      },
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增记录',
      formData: {
        id: null,
        location: '',
        code: '',
        name: '',
        type: '',
        purpose: '',
        in_number: 0,
        out_number: 0,
        remain: 0,
        unit: '台',
        add_user: '',
        remark: '',
        add_time: '',
        operation: 'in',  // in: 入库, out: 出库
        quantity: 1,      // 操作数量
        month: null
      },
      // 模拟数据
      mockRecords: [
        {
          id: 1,
          location: '京东商城',
          name: 'iPhone 15 Pro',
          type: '电子产品',
          purpose: '销售',
          in_number: 100,
          out_number: 0,
          remain: 100,
          unit: '台',
          add_user: '张三',
          remark: '新品到货',
          add_time: '2025-06-10 09:30:45',
          month: 6
        },
        {
          id: 2,
          location: '天猫超市',
          name: '华为Mate 60',
          type: '电子产品',
          purpose: '销售',
          in_number: 0,
          out_number: 50,
          remain: 50,
          unit: '台',
          add_user: '李四',
          remark: '客户订单',
          add_time: '2025-06-12 14:20:30',
          month: 6
        },
        {
          id: 3,
          location: '拼多多',
          name: '小米14 Ultra',
          type: '电子产品',
          purpose: '促销',
          in_number: 200,
          out_number: 0,
          remain: 200,
          unit: '台',
          add_user: '王五',
          remark: '活动备货',
          add_time: '2025-06-15 11:10:15',
          month: 6
        },
        {
          id: 4,
          location: '苏宁易购',
          name: 'OPPO Find X7',
          type: '电子产品',
          purpose: '展示',
          in_number: 30,
          out_number: 5,
          remain: 25,
          unit: '台',
          add_user: '赵六',
          remark: '门店调货',
          add_time: '2025-06-18 16:45:00',
          month: 6
        },
        {
          id: 5,
          location: '国美电器',
          name: 'vivo X100',
          type: '电子产品',
          purpose: '销售',
          in_number: 80,
          out_number: 20,
          remain: 60,
          unit: '台',
          add_user: '钱七',
          remark: '新品到货',
          add_time: '2025-06-20 10:30:00',
          month: 6
        },
        {
          id: 6,
          location: '物美超市',
          name: '蒙牛纯牛奶',
          type: '食品',
          purpose: '促销',
          in_number: 200,
          out_number: 0,
          remain: 200,
          unit: '箱',
          add_user: '孙八',
          remark: '库存补充',
          add_time: '2025-06-22 13:25:10',
          month: 6
        },
        {
          id: 7,
          location: '家乐福',
          name: '金龙鱼食用油',
          type: '食品',
          purpose: '正常补货',
          in_number: 150,
          out_number: 0,
          remain: 150,
          unit: '桶',
          add_user: '周九',
          remark: '新品到货',
          add_time: '2025-06-25 15:40:20',
          month: 6
        },
        {
          id: 8,
          location: '沃尔玛',
          name: '海飞丝洗发水',
          type: '日用品',
          purpose: '正常销售',
          in_number: 0,
          out_number: 60,
          remain: 90,
          unit: '瓶',
          add_user: '吴十',
          remark: '客户订单',
          add_time: '2025-06-28 11:15:05',
          month: 6
        }
      ]
    };
  },
  computed: {
    // 分页后的数据
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredRecords.slice(start, end);
    }
  },
  mounted() {
    this.loadRecords();
  },
  methods: {
    // 加载记录数据
    async loadRecords() {
      this.loading = true;
      
      try {
        // 尝试从后端获取数据
        const response = await axios.get('/api/statistics/remove/');
        
        if (response.data && Array.isArray(response.data)) {
          this.records = response.data;
          this.filteredRecords = [...response.data];
          this.calculateStatistics();
          this.$message.success('数据加载成功');
        } else {
          this.errorMessage = '后端返回数据格式不正确';
          this.useMockData();
        }
      } catch (error) {
        console.error('加载数据出错:', error);
        this.errorMessage = `后端请求失败: ${error.message || '未知错误'}`;
        this.useMockData();
      } finally {
        this.loading = false;
      }
    },
    
    // 使用模拟数据
    useMockData() {
      setTimeout(() => {
        console.log('后端未响应，使用模拟数据');
        this.records = this.mockRecords;
        this.filteredRecords = [...this.mockRecords];
        this.calculateStatistics();
      }, 2000);
    },
    
    // 计算统计数据
    calculateStatistics() {
      if (!this.records || this.records.length === 0) return;
      
      this.statistics.totalIn = this.records.reduce((sum, item) => sum + item.in_number, 0);
      this.statistics.totalOut = this.records.reduce((sum, item) => sum + item.out_number, 0);
      this.statistics.remainTotal = this.records.reduce((sum, item) => sum + item.remain, 0);
      
      // 计算不同商品的数量
      const uniqueProducts = new Set(this.records.map(item => item.name));
      this.statistics.productCount = uniqueProducts.size;
    },
    
    // 处理搜索
    handleSearch() {
      this.filteredRecords = this.records.filter(item => {
        // 公司名称筛选
        if (this.searchForm.location && 
            !item.location.includes(this.searchForm.location)) {
          return false;
        }
        
        // 商品名称筛选
        if (this.searchForm.name && 
            !item.name.includes(this.searchForm.name)) {
          return false;
        }
        
        // 操作类型筛选
        if (this.searchForm.operationType) {
          if (this.searchForm.operationType === 'in' && item.in_number === 0) {
            return false;
          }
          if (this.searchForm.operationType === 'out' && item.out_number === 0) {
            return false;
          }
        }
        
        // 日期范围筛选
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          const start = new Date(this.searchForm.dateRange[0]);
          const end = new Date(this.searchForm.dateRange[1]);
          end.setDate(end.getDate() + 1); // 包含结束日期的0点
          
          const itemDate = new Date(item.add_time);
          if (itemDate < start || itemDate >= end) {
            return false;
          }
        }
        
        return true;
      });
      
      this.currentPage = 1;
    },
    
    // 重置筛选条件
    resetSearch() {
      this.searchForm = {
        location: '',
        name: '',
        operationType: '',
        dateRange: []
      };
      this.filteredRecords = [...this.records];
      this.currentPage = 1;
    },
    
    // 处理表格行选择
    handleSelectionChange(val) {
      this.selectedRecords = val;
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },
    
    // 当前页码变化
    handleCurrentChange(page) {
      this.currentPage = page;
    },
    
    // 添加新记录
    handleAdd() {
      this.dialogTitle = '新增记录';
      this.formData = {
        id: null,
        location: '',
        code: '',
        name: '',
        type: '',
        purpose: '',
        in_number: 0,
        out_number: 0,
        remain: 0,
        unit: '台',
        add_user: this.userInfo.name,
        remark: '',
        add_time: new Date().toISOString().replace('T', ' ').substring(0, 19),
        operation: 'in',
        quantity: 1,
        month: new Date().getMonth() + 1
      };
      this.dialogVisible = true;
    },
    
    // 编辑记录
    handleEdit(row) {
      this.dialogTitle = '编辑记录';
      this.formData = {
        ...row,
        operation: row.in_number > 0 ? 'in' : 'out',
        quantity: row.in_number > 0 ? row.in_number : row.out_number
      };
      this.dialogVisible = true;
    },
    
    // 提交表单数据
    async handleSubmit(formData) {
      this.formData = formData;
      
      // 更新实际数字字段
      if (this.formData.operation === 'in') {
        this.formData.in_number = this.formData.quantity;
        this.formData.out_number = 0;
      } else {
        this.formData.out_number = this.formData.quantity;
        this.formData.in_number = 0;
      }
      
      try {
        if (this.formData.id) {
          // 更新记录
          const response = await axios.put(`/api/statistics/remove/${this.formData.id}`, this.formData);
          const index = this.records.findIndex(item => item.id === this.formData.id);
          if (index !== -1) {
            this.records.splice(index, 1, response.data);
            this.$message.success('记录更新成功');
          }
        } else {
          // 新增记录
          const response = await axios.post('/api/statistics/remove/', this.formData);
          this.records.unshift(response.data);
          this.$message.success('记录添加成功');
        }
        
        // 重置过滤记录
        this.filteredRecords = [...this.records];
        this.calculateStatistics();
      } catch (error) {
        console.error('保存记录失败:', error);
        this.errorMessage = `保存失败: ${error.message || '未知错误'}`;
      }
    },
    
    // 删除记录
    handleDelete(row) {
      this.$confirm('确定要删除这条记录吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete(`/api/statistics/remove/${row.id}`);
          
          // 从原始记录中删除
          const index = this.records.findIndex(item => item.id === row.id);
          if (index !== -1) {
            this.records.splice(index, 1);
            this.filteredRecords = this.filteredRecords.filter(item => item.id !== row.id);
            this.calculateStatistics();
            this.$message.success('删除成功');
          }
        } catch (error) {
          console.error('删除记录失败:', error);
          this.errorMessage = `删除失败: ${error.message || '未知错误'}`;
        }
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 批量删除
    batchDelete() {
      if (this.selectedRecords.length === 0) return;
      
      this.$confirm(`确定要删除选中的 ${this.selectedRecords.length} 条记录吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedRecords.map(item => item.id);
          await axios.post('/api/statistics/remove/batch-delete', { ids });
          
          // 从记录中删除
          this.records = this.records.filter(item => !ids.includes(item.id));
          this.filteredRecords = this.filteredRecords.filter(item => !ids.includes(item.id));
          this.calculateStatistics();
          this.selectedRecords = [];
          this.$message.success(`成功删除 ${ids.length} 条记录`);
        } catch (error) {
          console.error('批量删除失败:', error);
          this.errorMessage = `批量删除失败: ${error.message || '未知错误'}`;
        }
      }).catch(() => {
        // 取消删除
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.stats-container {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  height: 100px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.stat-content {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value .value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-right: 5px;
}

.stat-value .unit {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon i {
  font-size: 36px;
  color: white;
}

.filter-card {
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
  text-align: right;
}

.el-table .in-number {
  color: #67C23A;
  font-weight: bold;
}

.el-table .out-number {
  color: #F56C6C;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.error-message {
  margin-bottom: 20px;
}
</style>